﻿namespace Blaze.ConfigExportTool
{
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Linq;
    using System.Reflection;
    using Configuration;
    using log4net;

    public class Program
    {
        public static void Main(string[] args)
        {
            var exporters = getExporters().ToArray();
            var isDev = getDev(args);

            foreach (var exporter in exporters)
            {
                exporter.IsDevelopment = isDev;
                try
                {
                    exporter.Execute();
                    Console.WriteLine("导出成功：{0}", exporter.GetType().Name);
                }
                catch (ExportException e)
                {
                    mLog.ErrorFormat("导出失败：{0}", e.Message);
                }
                catch (Exception e)
                {
                    var msg = string.Format("{0}\r\n{1}", e.Message, e.StackTrace);
                    mLog.ErrorFormat("导出失败：{0}", msg);
                }
            }
            Console.WriteLine();
            Console.WriteLine("按任意键退出...");
            Console.ReadLine();
        }

        private static bool getDev(string[] args)
        {
            return args.Contains("-dev");
        }

        private static IEnumerable<ExporterBase> getExporters()
        {
            var blazeSection = ConfigurationManager.GetSection("blaze") as BlazeSection;
            if (blazeSection == null)
                yield break;
            foreach (ExporterSection config in blazeSection.Exporters)
            {
                ExporterBase exporter;
                try
                {
                    var assembly = Assembly.Load(config.AssemblyName);
                    if (assembly == null)
                    {
                        mLog.WarnFormat("获取导出器类型失败：找不到程序集 {0}", config.AssemblyName);
                        continue;
                    }

                    var type = assembly.GetType(config.TypeName);
                    if (type == null)
                    {
                        mLog.WarnFormat("获取导出器类型失败：找不到类型 {0}", config.TypeName);
                        continue;
                    }

                    exporter = (ExporterBase) Activator.CreateInstance(type);
                }
                catch (Exception e)
                {
                    mLog.WarnFormat("创建导出器失败：{0}", e.Message);
                    continue;
                }
                mLog.DebugFormat("导出器 {0} 已找到", exporter.GetType().FullName);
                yield return exporter;
            }
        }

        private static readonly ILog mLog = LogManager.GetLogger(typeof (Program));
    }
}